import express from 'express';
import { FileStorage } from '../FileStorage';
import type { Memory } from '../FileStorage';

const router = express.Router();

// 获取所有记忆
router.get('/memorys', async (req, res) => {
  try {
    const fileStorage = new FileStorage();
    await fileStorage.init();
    const memorys = await fileStorage.getEntities<Memory>('memorys');
    res.json({
      code: 200,
      data: memorys,
      message: 'success'
    });
  } catch (error) {
    console.error('获取记忆列表失败:', error);
    res.status(500).json({
      code: 500,
      error: '获取记忆列表失败'
    });
  }
});

// 根据ID获取记忆
router.get('/memorys/:id', async (req:any, res:any) => {
  try {
    const { id } = req.params;
    const fileStorage = new FileStorage();
    await fileStorage.init();
    const memory = await fileStorage.findEntityById<Memory>('memorys', id);
    
    if (!memory) {
      return res.status(404).json({
        code: 404,
        error: '未找到指定的记忆'
      });
    }
    
    res.json({
      code: 200,
      data: memory,
      message: 'success'
    });
  } catch (error) {
    console.error('获取记忆失败:', error);
    res.status(500).json({
      code: 500,
      error: '获取记忆失败'
    });
  }
});

// 创建新记忆
router.post('/memorys', async (req, res) => {
  try {
    const memoryData: Memory = req.body;
    const fileStorage = new FileStorage();
    await fileStorage.init();
    const newMemory = await fileStorage.addEntity<Memory>('memorys', memoryData);
    
    res.status(201).json({
      code: 201,
      data: newMemory,
      message: '记忆创建成功'
    });
  } catch (error) {
    console.error('创建记忆失败:', error);
    res.status(500).json({
      code: 500,
      error: '创建记忆失败'
    });
  }
});

// 更新记忆
router.put('/memorys/:id', async (req:any, res:any) => {
  try {
    const { id } = req.params;
    const updateData: Partial<Memory> = req.body;
    const fileStorage = new FileStorage();
    await fileStorage.init();
    const updatedMemory = await fileStorage.updateEntity<Memory>('memorys', id, updateData);
    
    if (!updatedMemory) {
      return res.status(404).json({
        code: 404,
        error: '未找到指定的记忆'
      });
    }
    
    res.json({
      code: 200,
      data: updatedMemory,
      message: '记忆更新成功'
    });
  } catch (error) {
    console.error('更新记忆失败:', error);
    res.status(500).json({
      code: 500,
      error: '更新记忆失败'
    });
  }
});

// 删除记忆
router.delete('/memorys/:id', async (req:any, res:any) => {
  try {
    const { id } = req.params;
    const fileStorage = new FileStorage();
    await fileStorage.init();
    const result = await fileStorage.deleteEntity('memorys', id);
    
    if (!result) {
      return res.status(404).json({
        code: 404,
        error: '未找到指定的记忆'
      });
    }
    
    res.json({
      code: 200,
      message: '记忆删除成功'
    });
  } catch (error) {
    console.error('删除记忆失败:', error);
    res.status(500).json({
      code: 500,
      error: '删除记忆失败'
    });
  }
});

export default router;